from urllib import quote, urlencode
from logging import getLogger
from sets import Set

try:
    from xml.etree import cElementTree as etree
except ImportError:
    from elementtree import ElementTree as etree

from zope.interface import implements

from plone.memoize.view import memoize, memoize_contextless

from meercat.ui.plone.browser.content.base import BaseView
from meercat.ui.plone.browser.content.interfaces import IMeercatResourceView


log = getLogger('meercat.ui.plone')


class ResourceView(BaseView):
    implements(IMeercatResourceView)
    
    def __init__(self, *args, **kwargs):
        super(ResourceView, self).__init__(*args, **kwargs)
        
        self._resource = None
        self._id = self.request.get('id',None)
        if self._id:
            self._resource = self.manager.getResource(self._id)
    
    @property
    @memoize
    def absolute_url(self):
        return self.request.URL
    
    @property
    @memoize
    def full_url(self):
        return "%s?%s" % (self.request.URL,urlencode(self.request.form))
    
    def hasResource(self):
        return bool(self._resource)
    
    @property
    def holdings(self):
        if self.resource:
            return sum(map(lambda i: i.get('holdings',[]),
                           self.resource['instances']),[])
        return None
    
    @property
    def resource(self):
        return self._resource
    
    @property
    def identifier(self):
        return self._id
    
    def getFields(self):
        if not self.resource:
            return []
        
        set = Set()
        
        map(set.add, self.resource.iterkeys())
        
        for instance in self.resource.get('instances',[]):
            map(set.add, instance.iterkeys())
        
        set.discard('instances')
        set.discard('holdings')
        set.discard('url')
        
        return set
        
    
    def getField(self, name):
        if not self.resource:
            return None
        
        output = self.resource.get(name,Set())
        if self.resource.get('instances'):
            for instance in self.resource.get('instances'):
                output.update(instance.get(name,Set()))
        return list(filter(lambda v: v, output))
    
    def getResource(self):
        if self._resource:
            return etree.tostring(self._resource.getroot())
        
        return self._resource